package com.gzu.finalwork.user.service;


import com.gzu.finalwork.admin.service.EmailSettingsService;
import com.gzu.finalwork.entity.admin.EmailSettings;
import com.gzu.finalwork.entity.user.EmailMessage;
import com.gzu.finalwork.user.config.RabbitMQConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.Properties;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailService {

    private final RabbitTemplate rabbitTemplate;

    @Autowired
    private EmailSettingsService emailSettingsService;

    // 发送邮件消息到队列
    public void sendEmailMessage(EmailMessage emailMessage) {
        try {
            rabbitTemplate.convertAndSend(
                    RabbitMQConfig.EMAIL_EXCHANGE,
                    RabbitMQConfig.EMAIL_ROUTING_KEY,
                    emailMessage
            );
            log.info("邮件消息已发送到队列: {}", emailMessage);
        } catch (Exception e) {
            log.error("发送邮件消息到队列失败: {}", e.getMessage(), e);
        }
    }

    // 消费邮件消息队列
    @RabbitListener(queues = RabbitMQConfig.EMAIL_QUEUE)
    public void processEmailMessage(EmailMessage emailMessage) {
        try {
            log.info("开始处理邮件消息: {}", emailMessage);

            // 发送实际邮件
            sendActualEmail(emailMessage);

            log.info("邮件发送成功: 邮箱={}, 主题={}", emailMessage.getToEmail(), emailMessage.getSubject());
        } catch (Exception e) {
            log.error("处理邮件消息失败: {}", e.getMessage(), e);
            // 这里可以实现重试机制或者将失败消息存储到数据库
        }
    }

    // 发送实际邮件
    private void sendActualEmail(EmailMessage emailMessage) {
        try {
            // 获取邮件配置
            EmailSettings emailSettings = emailSettingsService.getEmailSettings();
            if (emailSettings == null) {
                log.error("邮件配置不存在，无法发送邮件");
                return;
            }

            // 创建邮件发送器
            JavaMailSenderImpl mailSender = createMailSender(emailSettings);

            // 创建邮件消息
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(emailSettings.getSenderEmail());
            message.setTo(emailMessage.getToEmail());
            message.setSubject(emailMessage.getSubject());
            message.setText(emailMessage.getContent());

            // 发送邮件
            mailSender.send(message);
            log.info("邮件发送成功: {} -> {}", emailSettings.getSenderEmail(), emailMessage.getToEmail());

        } catch (Exception e) {
            log.error("发送邮件失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    // 创建邮件发送器
    private JavaMailSenderImpl createMailSender(EmailSettings emailSettings) {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(emailSettings.getSmtpServer());
        mailSender.setPort(emailSettings.getSmtpPort());
        mailSender.setUsername(emailSettings.getSenderEmail());
        mailSender.setPassword(emailSettings.getEmailPassword());

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "false");

        if (emailSettings.getUseSsl() != null && emailSettings.getUseSsl()) {
            props.put("mail.smtp.ssl.enable", "true");
        }

        return mailSender;
    }
}